# apps/users/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser

class QBUser(AbstractUser):
    ROLE_CHOICES = (
        ('admin', '管理员'),
        ('teacher', '教师'),
        ('editor', '编辑'),
    )

    username = models.CharField(max_length=150, unique=True)
    email = models.EmailField(unique=True, null=True, blank=True)
    full_name = models.CharField(max_length=100)
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='teacher')
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    date_joined = models.DateTimeField(auto_now_add=True)
    last_login = models.DateTimeField(null=True, blank=True)
    # 新增：多对多角色（可选，用于更复杂场景）
    roles = models.ManyToManyField('roles.Role', blank=True, verbose_name="角色")
    tenant = models.ForeignKey('tenants.Tenant', on_delete=models.CASCADE, null=True, verbose_name="租户")
    


    # 修复冲突：修改 related_name
    groups = models.ManyToManyField(
        'auth.Group',
        verbose_name='groups',
        blank=True,
        help_text='The groups this user belongs to.',
        related_name='qbuser_set',          # ✅ 关键：避免与 auth.User 冲突
        related_query_name='qbuser',
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        verbose_name='user permissions',
        blank=True,
        help_text='Specific permissions for this user.',
        related_name='qbuser_set',          # ✅ 关键
        related_query_name='qbuser',
    )

    def __str__(self):
        return self.username

    class Meta:
        db_table = 'qb_users'
        verbose_name = '用户'
        verbose_name_plural = '用户管理'